package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.db.GoodsDetailMsBean
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AreaItemBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.GoodsDetailBean
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback

/**
 * 单个商品（下单）
 * */
class ConfirmSingleTakeOrderFragment : BaseFragmentEx(), View.OnClickListener,
    RadioGroup.OnCheckedChangeListener {

    companion object {
        fun newInstance(mDetailBean: GoodsDetailBean?): ConfirmSingleTakeOrderFragment {
            val args = Bundle()
            args.putSerializable("mDetailBean", mDetailBean)
            val fragment = ConfirmSingleTakeOrderFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var mDetailBean: GoodsDetailBean? = null

    //商品图片
    private lateinit var icon: ImageView

    //商品名称
    private lateinit var goodsName: TextView

    //商品型号
    private lateinit var goodsTyp: TextView

    //商品单价
    private lateinit var goodsPrice: TextView

    //商品运输费
    private lateinit var deliveryCost: TextView

    //付款方式
    private var payWay: RadioGroup? = null

    //选择数量
    private lateinit var selectCount: TextView

    //选择数量（减）
    private lateinit var discount: ImageView

    //选择数量（加）
    private lateinit var plus: ImageView

    //共计花费
    private lateinit var allCostTv: TextView

    //立即购买
    private lateinit var toBuy: View

    private val iconType = AppGlobals.getApplication().getString(R.string.wallet_sst)

//    private var cml = selectorIcon()

    private var cml = AppGlobals.getApplication().getString(R.string.wallet_fu_li_scored)

    private lateinit var orderDesc: EditText

    private var addressType: RadioGroup? = null

    private var deliveryInfo = DeliveryInfoFragment.newInstance()

    private var mDeliveryInfoAgency = DeliveryInfoAgencyFragment.newInstance()

    private val childFragment = arrayOf<BaseFragmentEx>(
        deliveryInfo, mDeliveryInfoAgency
    )

    private var currentIndex = 0

    private var lastIndex = 0

    private var mAgencyAddress: TextView? = null

    private val selectedAreaLs = mutableListOf<AreaItemBean?>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mDetailBean = arguments?.getSerializable("mDetailBean") as GoodsDetailBean
    }

    override fun getLayoutId(): Any {
        return R.layout.confirm_single_take_order_fragment
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        addressType = view.findViewById(R.id.addressType)



        mAgencyAddress = view.findViewById(R.id.mAgencyAddress)

        mAgencyAddress?.setOnClickListener(this)

        loadMultipleRootFragment(R.id.mDeliveryLayout, currentIndex, *childFragment)

//        loadRootFragment(R.id.mDeliveryLayout, deliveryInfo)

        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "确定订单"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        toBuy = view.findViewById(R.id.toBuy)
        orderDesc = view.findViewById(R.id.orderDesc)
        allCostTv = view.findViewById(R.id.allCostTv)
        selectCount = view.findViewById(R.id.selectCount)
        icon = view.findViewById(R.id.icon)
        goodsName = view.findViewById(R.id.goodsName)
        goodsTyp = view.findViewById(R.id.goodsTyp)
        goodsPrice = view.findViewById(R.id.goodsPrice)
        deliveryCost = view.findViewById(R.id.deliveryCost)

        payWay = view.findViewById(R.id.payWay)

        discount = view.findViewById(R.id.discount)
        plus = view.findViewById(R.id.plus)


        toBuy.setOnClickListener(this)
        discount.setOnClickListener(this)
        plus.setOnClickListener(this)

        addressType?.setOnCheckedChangeListener(this)
        payWay?.setOnCheckedChangeListener(this)

//        val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
//        val map = mapOf(
//            "orderId" to mDetailBean?.goods?.gid,
//            "uid" to user?.uid
//        )
//
//        RestClient.builder()
//            .url(R.string.queryOrderInfoById)
//            .raw(JSON.toJSONString(map))
//            .success {
//
//            }
//            .failure {
//
//            }.error { code, msg ->
//
//            }.build().post()


        val goods = mDetailBean?.goods
        GlideApp.with(this)
            .load(goods?.defaultImg)
            .centerCrop()
            .into(icon)

        goodsName.text = goods?.goodsName
        goodsTyp.text = "${goods?.selectedLabStr}"

//        goodsPrice.text = "${goods?.goodsPrice} $iconType 赠送${goods?.givenCml} $cml"

        val givenCml = "${goods?.givenCml}"

        goodsPrice.text = "${goods?.goodsPrice} $iconType " +
                _mActivity.getString(R.string.wallet_fu_li_scored)

        selectCount.text = goods?.selectedCount.toString()

        deliveryCost.text = goods?.goodsFareStr

        presentPrice(goods)
    }


    @SuppressLint("SetTextI18n")
    override fun onClick(v: View?) {
        when (v?.id) {

            R.id.mAgencyAddress -> {
                XPopup.Builder(_mActivity)
                    .asCustom(
                        SelectLocationPop(_mActivity)
                            .setIsAfterDistrict(true)
                            .setOnSelectListener(object : SelectLocationPop.OnSelectListener {

                                override fun onSelected(ls: List<AreaItemBean?>) {
                                    selectedAreaLs.clear()
                                    selectedAreaLs.addAll(ls)
                                    mAgencyAddress?.text = getSelectLocationName()
                                }
                            })
                    )
                    .show()
            }

            R.id.discount -> {
                val goods = mDetailBean?.goods
                val selectedCount = goods?.selectedCount ?: 0
                if (selectedCount > 1) {
                    goods?.selectedCount = selectedCount - 1
                    selectCount.text = goods?.selectedCount.toString()
                }
                presentPrice(goods)
            }
            R.id.plus -> {
                val goods = mDetailBean?.goods
                val selectedCount = goods?.selectedCount ?: 0
                goods?.selectedCount = selectedCount + 1
                selectCount.text = goods?.selectedCount.toString()
                presentPrice(goods)
            }

            R.id.toBuy -> {
                showPop()

            }
        }
    }

    private fun getSelectLocationName(): String {

        var string = StringBuilder()
        for (e in selectedAreaLs) {
            string.append(e?.areaName?.replace(",", "")).append(",")
        }

        if (string.lastIndexOf(",") != string.indexOf(",")) {
            string = string.deleteCharAt(string.lastIndexOf(","))
        }

        return string.toString()
    }

    private fun showPop() {
        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            toBuyNow()
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()
    }

    private fun toBuyNow() {


        val goods = mDetailBean?.goods

        val deliveryInfo = when (addressType?.checkedRadioButtonId) {
            R.id.defaultAddress -> deliveryInfo.getAddressSpot()
            R.id.agencyAddress -> mDeliveryInfoAgency.getInfo()
            else -> deliveryInfo.getAddressSpot()
        }
        if (deliveryInfo == null) {

            normalShortToast(_mActivity, "请添加收货地址")

            return
        }

        if (deliveryInfo.msgStr.isNotEmpty()) {

            normalShortToast(_mActivity, deliveryInfo.msgStr)

            return
        }

        val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val payType = when (payWay?.checkedRadioButtonId) {
            R.id.fu_lu_ji_fen -> 1
            R.id.leftMoney -> 0
            else -> 0
        }

        val aid = if (selectedAreaLs.isEmpty())
            "0"
        else
            "${selectedAreaLs[selectedAreaLs.size - 1]?.aid}"

        val map = mapOf(
            "areaIds" to deliveryInfo.areaIds,
            "goodsColor" to goods?.defaultSelectColorLab(),
            "goodsId" to goods?.gid,
            "goodsNums" to goods?.selectedCount,
            "goodsSize" to goods?.defaultSelectSizeLab(),
            "orderDesc" to orderDesc.text.toString(),
            "payType" to payType,
            "aid" to aid,
            "receiverAddr" to deliveryInfo.recAddr,
            "receiverName" to deliveryInfo.recName,
            "receiverPhone" to deliveryInfo.recPhone,
            "uId" to user?.uid,
        )
        RestClient.builder()
//            .url(R.string.saveShopOrder)
            .url(R.string.ys_saveShopOrder)
            .raw(JSON.toJSONString(map))
            .success {
                Toast.makeText(_mActivity, "下单成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(_mActivity)
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .failure {
                Toast.makeText(_mActivity, "下单失败", Toast.LENGTH_SHORT).show()
            }.build().post()
    }


    @SuppressLint("SetTextI18n")
    private fun presentPrice(goods: GoodsDetailMsBean?) {
        val allCost =
            (goods?.goodsPrice ?: 0) * (goods?.selectedCount ?: 1) + (goods?.goodsFare ?: 0)
        allCostTv.text =
            "$allCost $iconType"
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {

        if (group?.id == R.id.payWay) {
            return
        }

        if (group?.id == R.id.addressType) {
            when (checkedId) {
                R.id.defaultAddress -> {
                    currentIndex = 0
                }
                R.id.agencyAddress -> {
                    currentIndex = 1
                }
            }

            if (lastIndex == currentIndex) return

            val nextFragment = childFragment[currentIndex]

            showHideFragment(nextFragment, childFragment[lastIndex])

            lastIndex = currentIndex
        }

    }


}